package com.hogocloud.myframe.adapter

import android.graphics.Canvas
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.hogocloud.corelibrary.utils.LogUtils
import com.hogocloud.myframe.data.bean.SelectItemBean
import kotlinx.android.synthetic.main.item_select_top.view.*

/**
 * 自定义拖拽
 * Created by kuyue on 2017/6/19 下午5:42.
 * 邮箱:595327086@qq.com
 */

class PhotoDragCallBack(
    private val adapter: ReadDragAdapter, private val images: MutableList<SelectItemBean>//图片经过压缩处理
) : ItemTouchHelper.Callback() {

    private var mTarget: RecyclerView.ViewHolder? = null
    private var fromPosition: Int = 0
    private var toPosition: Int = 0
    private var dragVX: Int = 0
    private var dragVY: Int = 0
    private var isRightUp: Int = -1 // 0 错误；1正确
    private var dragFlags: Int = 0
    private var swipeFlags: Int = 0
    private var up: Boolean = false//手指抬起标记位

    private var dragListener: DragListener? = null

    /**
     * 设置item是否处理拖拽事件和滑动事件，以及拖拽和滑动操作的方向
     *
     * @param recyclerView
     * @param viewHolder
     * @return
     */
    override fun getMovementFlags(
        recyclerView: RecyclerView,
        viewHolder: RecyclerView.ViewHolder
    ): Int {
        //判断 recyclerView的布局管理器数据
        if (recyclerView.layoutManager is StaggeredGridLayoutManager || recyclerView.layoutManager is GridLayoutManager) {//设置能拖拽的方向
            dragFlags =
                ItemTouchHelper.UP or ItemTouchHelper.DOWN or ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
            swipeFlags = 0//0则不响应事件
        }
        return ItemTouchHelper.Callback.makeMovementFlags(dragFlags, swipeFlags)
    }

    /**
     * 当用户从item原来的位置拖动可以拖动的item到新位置的过程中调用
     *
     * @param recyclerView
     * @param viewHolder
     * @param target
     * @return
     */
    override fun onMove(
        recyclerView: RecyclerView,
        viewHolder: RecyclerView.ViewHolder,
        target: RecyclerView.ViewHolder
    ): Boolean {
        mTarget = target
        fromPosition = viewHolder.adapterPosition//得到item原来的position
        toPosition = target.adapterPosition//得到目标position
        val location = IntArray(2)
        target.itemView.iv_bottom.getLocationOnScreen(location)
        val rect = Rect(location[0] - viewHolder.itemView.iv_bottom.left,
            location[1] - viewHolder.itemView.iv_bottom.top,
            location[0] + target.itemView.iv_bottom.right - target.itemView.iv_bottom.left,
            location[1] + target.itemView.iv_bottom.bottom - target.itemView.iv_bottom.top)

        isRightUp = when {
            rect.contains(dragVX, dragVY) -> { //判断拖动的view是否在篮子的范围内
                when (images[fromPosition].type) {
                    images[toPosition].type -> {
                        1
                    }
                    else -> {
                        0
                    }
                }
            }
            else -> {
                -1
            }
        }

        return true
    }

    /**
     * 设置是否支持长按拖拽
     *
     * @return
     */
    override fun isLongPressDragEnabled(): Boolean {
        return false
    }

    /**
     * @param viewHolder
     * @param direction
     */
    override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {

    }

    /**
     * 当用户与item的交互结束并且item也完成了动画时调用
     *
     * @param recyclerView
     * @param viewHolder
     */
    override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
        super.clearView(recyclerView, viewHolder)
        adapter.notifyDataSetChanged()
        LogUtils.e("clear view")
        initData()
        dragListener?.clearView()
    }

    /**
     * 重置
     */
    private fun initData() {
        dragListener?.deleteState(false)
        dragListener?.dragState(false)
        up = false
    }

    /**
     * 自定义拖动与滑动交互
     *
     * @param c
     * @param recyclerView
     * @param viewHolder
     * @param dX
     * @param dY
     * @param actionState
     * @param isCurrentlyActive
     */
    override fun onChildDraw(
        c: Canvas,
        recyclerView: RecyclerView,
        viewHolder: RecyclerView.ViewHolder,
        dX: Float,
        dY: Float,
        actionState: Int,
        isCurrentlyActive: Boolean
    ) {
        val location = IntArray(2)
        viewHolder.itemView.iv_top.getLocationOnScreen(location)
        dragVX = location[0]
        dragVY = location[1]

        if (up) {
            when (isRightUp) {
                1 -> {
                    images[toPosition].topPic = images[fromPosition].bottomPic
                    images[fromPosition].isVisible = false
                    //放到正确的篮子时先隐藏itemView
                    viewHolder.itemView.visibility = View.INVISIBLE
                }
                0 -> {
                    if (mTarget != null && toPosition > adapter.itemCount / 2) {
                        images[toPosition].playErrorAnim = true
                        adapter.notifyItemChanged(toPosition)
                    }}
                else -> viewHolder.itemView.visibility = View.VISIBLE
            }
        }
        super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
    }

    /**
     * 当长按选中item的时候（拖拽开始的时候）调用
     *
     * @param viewHolder
     * @param actionState
     */
    override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
        if (ItemTouchHelper.ACTION_STATE_DRAG == actionState && dragListener != null) {
            dragListener!!.dragState(true)
        }
        LogUtils.e("selected : $actionState")
        super.onSelectedChanged(viewHolder, actionState)
    }

    /**
     * 设置手指离开后ViewHolder的动画时间，在用户手指离开后调用
     *
     * @param recyclerView
     * @param animationType
     * @param animateDx
     * @param animateDy
     * @return
     */
    override fun getAnimationDuration(
        recyclerView: RecyclerView,
        animationType: Int,
        animateDx: Float,
        animateDy: Float
    ): Long {
        //手指放开
        up = true
        return super.getAnimationDuration(recyclerView, animationType, animateDx, animateDy)
    }

    interface DragListener {
        /**
         * 用户是否将 item拖动到删除处，根据状态改变颜色
         *
         * @param delete
         */
        fun deleteState(delete: Boolean)

        /**
         * 是否于拖拽状态
         *
         * @param start
         */
        fun dragState(start: Boolean)

        /**
         * 当用户与item的交互结束并且item也完成了动画时调用
         */
        fun clearView()
    }

     fun setDragListener(dragListener: DragListener) {
        this.dragListener = dragListener
    }

}
